import {defineStore} from 'pinia';
import { Session } from '../utils/storage'

interface UserState {
    isAuthenticated: boolean;
    token: string | null;
    refreshToken: string | null;
    userInfo: { username: string } | null;
}
export const useUserStore = defineStore('user', {
    state: () => ({
        isAuthenticated: false,
        token: "",
        refreshToken: "",
        userInfo: "",
    }),
    actions: {
        login(token: string, refreshToken: string, userInfo: { username: string }) {
            this.isAuthenticated = true;
            this.token = token;
            this.refreshToken = refreshToken;
            this.userInfo = userInfo;

            Session.set('token', token);
            Session.set('refresh_token', refreshToken);
            Session.set('userInfo', userInfo);
        },
        logout() {
            this.isAuthenticated = false;
            this.token = "";
            this.refreshToken = "";
            this.userInfo = "";

            Session.remove('token');
            Session.remove('refresh_token');
            Session.remove('userInfo');
        },
        restoreSession() {
            console.log('restoreSession111111111');
            const token = Session.get('token');
            const userInfo = Session.get('userInfo');

            if (token && userInfo) {
                this.isAuthenticated = true;
                this.token = token;
                this.userInfo = userInfo;
            }
        }
    },
});
